const fs = require('fs');
const path = require('path');
const { VM } = require('vm2');
const { NPC, Player } = require('./sandbox');

class ScriptRunner {
  constructor() {
    this.sessions = new Map(); // 存储脚本执行状态
  }

  async runScript(npcId, playerData, action, inputData) {
    const scriptPath = path.join(__dirname, './npc', `${npcId}.js`);
    console.log(scriptPath);
    let scriptCode;

    try {
      scriptCode = fs.readFileSync(scriptPath, 'utf-8');
    } catch (err) {
      throw new Error(`NPC script not found: ${npcId}`);
    }

    const playerId = playerData.id;
    const sessionId = `${playerId}-${npcId}`;
    let context = this.sessions.get(sessionId);

    const player = new Player(playerData);
    const responses = [];

    const send = (data) => responses.push(data);

    let npc;
    if (!context) {
      // 首次运行
      npc = new NPC(npcId, player, send);
      context = { npc, player, scriptCode, position: 'start' };
    } else {
      // 恢复中断的脚本
      npc = context.npc;
      npc.send = send;
      npc.waitForInput = () => inputData; // 注入用户输入
      context.position = 'resumed';
    }

    try {
      const vm = new VM({
        timeout: 3000,
        sandbox: { npc, player },
        eval: false
      });

      vm.run(context.scriptCode);

    } catch (err) {
      if (err.message === 'PAUSE_SCRIPT_EXECUTION') {
        // 脚本暂停，等待用户输入
        this.sessions.set(sessionId, context);
        return { waiting: true, responses };
      }

      // 其他错误
      console.error('Script error:', err);
      return { error: err.message };
    }

    // 脚本执行完毕，清理会话
    this.sessions.delete(sessionId);
    return { waiting: false, responses, player: player }; // 返回更新后的玩家
  }

  // 获取等待中的会话（用于调试）
  getSessions() {
    return Array.from(this.sessions.entries());
  }
}

module.exports = new ScriptRunner();